package tunnel;

import okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * 小象代理隧道代理示例 - JAVA，类库 okhttp
 *
 * @author xxdl
 */
public class OkHttpDemo {
    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String proxyHost = "http-dynamic.xiaoxiangdaili.com";
    private static Integer proxyPort = 10030;
    private static String targetUrl = "http://httpbin.org/ip";

    public static void main(String[] args) throws IOException {
        // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

        Authenticator authenticator = new Authenticator() {
            public Request authenticate(Route route, Response response) {
                String credential = Credentials.basic(appKey, appSecret);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)
                        .build();
            }
        };

        OkHttpClient client = new OkHttpClient.Builder()
                .proxy(proxy)
                .proxyAuthenticator(authenticator)
                .build();

        Request request = new Request.Builder()
                .url(targetUrl)
                .header("Accept-Encoding", "gzip")
                .header("Connection", "close")
                .build();

        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());

    }
}
